<template>
  <el-row>
    <el-card>
      <el-row>
        <el-col :span="10" style="font-size: 20px;line-height: 50px">
          {{ $t('productCenter.userLevel.title') }}
        </el-col>
        <el-col :span="14" style="text-align: right">
          <el-button :loading="realtimeLoading" @click="realtimeUpdate">{{ $t('productCenter.userLevel.liveUpdate') }}</el-button>
          <el-button @click="add">{{ $t('productCenter.userLevel.add') }}</el-button>
        </el-col>
      </el-row>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="inputData" :placeholder="$t('common.input')" class="input-with-select">
            <el-select slot="prepend" v-model="selectData">
              <el-option
                v-for="(item, index) in $t('productCenter.userLevel.input')"
                :key="index"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('productCenter.userLevel.list.product')">
          <el-select v-model="searchForm.productId" clearable :placeholder="$t('productCenter.userLevel.select')" style="width: 100%">
            <el-option
              v-for="item in loanProductData"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          prop="id"
          :label="tableText['id']"
          min-width="100"
        />
        <el-table-column
          fixed="left"
          prop="userLevelName"
          :label="tableText['name']"
          min-width="120"
        />
        <el-table-column
          prop="createTime"
          :label="tableText['creationTime']"
          min-width="170"
        />
        <el-table-column
          prop="modifyTime"
          :label="tableText['updateTime']"
          min-width="170"
        />
        <el-table-column
          prop="modifyOperatorName"
          :label="tableText['operator']"
          min-width="120"
        />
        <el-table-column
          prop="repetitionLoanNum"
          :label="tableText['pastSuccessfulBorrowings']"
          min-width="150"
        />
        <el-table-column
          prop="historyOverdueNum"
          :label="tableText['historicalOverdue']"
          min-width="150"
        />
        <el-table-column
          prop="lastNormalSettle"
          :label="tableText['whetherSettle']"
          min-width="180"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['lastNormalSettle'], 'type') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="lastDueDays"
          :label="tableText['lastOverdueDays']"
          min-width="150"
        />
        <el-table-column
          prop="telecomScore"
          :label="tableText['telecomScore']"
          min-width="150"
        />
        <el-table-column
          prop="creditScore"
          :label="tableText['creditScore']"
          min-width="150"
        />
        <el-table-column
          prop="historyOverdueNum"
          :label="tableText['historicalOverdue']"
          min-width="150"
        />
        <el-table-column
          prop="loanProductIdList"
          :label="tableText['optional']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ showLoanProduct(scope.row['loanProductIdList']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="showLoanProductIdList"
          :label="tableText['notOptional']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ showLoanProduct(scope.row['showLoanProductIdList']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="freeDayInterestRate"
          :label="tableText['freeDayInterestRate']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['freeDayInterestRate'] ? `${mulValue(scope.row['freeDayInterestRate'], 100)} %` : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="freeServiceFeeRate"
          :label="tableText['freeServiceFeeRate']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['freeServiceFeeRate'] ? `${mulValue(scope.row['freeServiceFeeRate'], 100)} %` : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          :label="tableText['status']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['status'], 'state') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="editItem(scope.row)">{{ $t('common.operate.edit') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <user-level-dialog
      ref="userLevelDialog"
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      :loan-product-data="loanProductData"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getLoanProduct, realtimeUserLevel, getUserLevel } from '@/api/product'
import UserLevelDialog from '@/components/product/user-level-dialog.vue'
import { mul } from '@/utils/method'
export default {
  name: 'UserLevel',
  components: {
    UserLevelDialog
  },
  data() {
    return {
      loading: false,
      editDialog: false,
      tableData: [],
      inputData: null,
      selectData: 'id',
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      loanProductData: [],
      loanProductObj: {},
      realtimeLoading: false,
      chooseItem: {
        id: null,
        userLevelName: null,
        loanProductIdList: [],
        showLoanProductIdList: [],
        freeDayInterestRate: null,
        freeServiceFeeRate: null,
        status: 1,
        rState: false,
        repetitionLoanNum: null,
        hState: false,
        historyOverdueNum: null,
        lState: false,
        lastNormalSettle: null,
        tState: false,
        telecomScore: null,
        cState: false,
        creditScore: null,
        dState: false,
        lastDueDays: null
      }
    }
  },
  mounted() {
    this.tableText = this.$t('productCenter.userLevel.list')
    this.getLoanProductData()
    this.getData()
  },
  methods: {
    getLoanProductData() {
      getLoanProduct()
        .then(res => {
          if (res.success) {
            this.loanProductObj = res.data
            this.loanProductData = []
            Object.keys(res.data).forEach(v => {
              const obj = {
                desc: res.data[v],
                value: v
              }
              this.loanProductData.push(obj)
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        id: null,
        userLevelName: null,
        productId: null
      }
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.selectData = 'id'
      this.inputData = null
      this.getData()
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        productId: this.searchForm.productId
      }
      if (this.selectData && this.inputData) {
        data[this.selectData] = this.inputData
      }
      return data
    },
    getData() {
      this.loading = true
      getUserLevel(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    realtimeUpdate() {
      this.realtimeLoading = true
      realtimeUserLevel()
        .then(res => {
          this.realtimeLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tips.operateSuccess'))
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.realtimeLoading = false
          this.$message.error(err.message)
        })
    },
    add() {
      this.choose({})
      this.editDialog = true
      this.$refs.userLevelDialog.getOptional()
      this.$refs.userLevelDialog.getNotOptional()
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    editItem(item) {
      this.choose(item)
      this.editDialog = true
      this.$refs.userLevelDialog.getOptional()
      this.$refs.userLevelDialog.getNotOptional()
    },
    choose(param) {
      this.chooseItem.id = param.id
      this.chooseItem.userLevelName = param.userLevelName
      this.chooseItem.loanProductIdList = param.loanProductIdList ? param.loanProductIdList.map(v => {
        return v + ''
      }) : []
      this.chooseItem.showLoanProductIdList = param.showLoanProductIdList ? param.showLoanProductIdList.map(v => {
        return v + ''
      }) : []
      this.chooseItem.status = param.status
      this.chooseItem.rState = !!(param.repetitionLoanNum)
      this.chooseItem.hState = !!(param.historyOverdueNum)
      this.chooseItem.lState = !!(param.lastNormalSettle)
      this.chooseItem.tState = !!(param.telecomScore)
      this.chooseItem.cState = !!(param.creditScore)
      this.chooseItem.dState = !!(param.lastDueDays)
      this.chooseItem.freeDayInterestRate = param.freeDayInterestRate ? mul(param.freeDayInterestRate, 100) : 0
      this.chooseItem.freeServiceFeeRate = param.freeServiceFeeRate ? mul(param.freeServiceFeeRate, 100) : 0
      this.chooseItem.repetitionLoanNum = param.repetitionLoanNum
      this.chooseItem.historyOverdueNum = param.historyOverdueNum
      this.chooseItem.lastNormalSettle = param.lastNormalSettle !== null ? param.lastNormalSettle : 1
      this.chooseItem.telecomScore = param.telecomScore
      this.chooseItem.creditScore = param.creditScore
      this.chooseItem.lastDueDays = param.lastDueDays
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    editSuccess() {
      this.getData()
    },
    setValue(val, data) {
      const name = this.$t(`productCenter.userLevel.${data}`).filter(item => {
        return item.value === val
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    showLoanProduct(data) {
      if (Array.isArray(data)) {
        const arr = []
        data.forEach(v => {
          arr.push(this.loanProductObj[v])
        })
        return arr.join(',  ')
      }
    },
    mulValue(a, b) {
      return mul(a, b)
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-divider{
    margin: 0 0 20px 0;
  }
  .el-card{
    margin: 10px;
  }
  .el-select{
    min-width: 150px;
  }
  .el-input{
    width: 400px;
  }
</style>
